/*
 * @lc app=leetcode.cn id=200 lang=golang
 *
 * [200] 岛屿数量
 */

// 没看明白哪不对
// @lc code=start
func numIslands(grid [][]byte) (ans int) {
	var dfs func(i, j int)
	dfs = func(i, j int) {
		if i >= 0 && i < len(grid) && j >= 0 && j < len(grid[i]) && grid[i][j] == 1 {
			grid[i][j] = 0
			dfs(i, j+1)
			dfs(i, j-1)
			dfs(i+1, j)
			dfs(i-1, j)
		}
	}

	i, j := getIslandsIndex(grid)
	for i >= 0 && j >= 0 {
		ans++
		dfs(i, j)
		i, j = getIslandsIndex(grid)
	}

	return
}

func getIslandsIndex(grid [][]byte) (int, int) {
	for i := 0; i < len(grid); i++ {
		for j := 0; j < len(grid[i]); j++ {
			if grid[i][j] == 1 {
				return i, j
			}
		}
	}
	return -1, -1
}

// @lc code=end

